package net.bwie.realtime.vehicle.job2;

import com.alibaba.fastjson.JSON;
import net.bwie.realtime.vehicle.utils.KafkaUtil;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

/**
 * @Author: FuHe
 * @Date: 2025/6/7
 */
public class VehicleEtlJob2 {
    public static void main(String[] args) throws Exception {
        // 设置执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        // 读取数据源 kafka
        DataStream<String> kafkaStream = KafkaUtil.consumerKafka(env, "vehicle-data");
//        kafkaStream.print();
        // 处理数据
        DataStream<String> processStream = processLog(kafkaStream);
//        processStream.print();
        KafkaUtil.producerKafka(processStream, "vehicle-data-log");
        env.execute("VehicleEtlJob2");
    }

    private static DataStream<String> processLog(DataStream<String> kafkaStream) {
        OutputTag<String> dirtyTag = new OutputTag<String>("dirty-tag") {
        };
        SingleOutputStreamOperator<String> process = kafkaStream.process(
                new ProcessFunction<String, String>() {
                    @Override
                    public void processElement(String value, ProcessFunction<String, String>.Context ctx, Collector<String> out) throws Exception {
                        try {
                            // 解析JSON字符串
                            JSON.parseObject(value);
                            // 没有异常，正常数据，主流输出
                            out.collect(value);
                        } catch (Exception e) {
                            // 脏数据 测流输出
                            ctx.output(dirtyTag, value);
                        }
                    }
                }
        );
        DataStream<String> dirtyTagOutput = process.getSideOutput(dirtyTag);
        KafkaUtil.producerKafka(dirtyTagOutput, "vehicle-log-dirty");
        return process;
    }
}
